const app = getApp();

Page({
  data: {
    title: '',
    content: '',
    petTypes: ['狗狗', '猫咪', '兔子', '其他'],
    petTypeIndex: 0,
    price: '',
    location: '',
    startDate: '',
    endDate: '',
    canSubmit: false,
    loading: false
  },

  onLoad() {
    console.log('📝 Create post page loaded');
    this.checkLogin();
  },

  onShow() {
    console.log('📝 Create post page shown');
    // 每次显示页面时都检查登录状态
    this.checkLogin();
  },

  checkLogin() {
    console.log('🔍 Checking login in create post page...');
    if (!app.globalData.userInfo || !app.globalData.token) {
      console.log('❌ User not logged in, redirecting to login');
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/user/login/login' });
          }, 1500);
        }
      });
      return false;
    }
    console.log('✅ User is logged in, can create post');
    console.log('User ID:', app.globalData.userInfo.id);
    console.log('Token available:', !!app.globalData.token);
    return true;
  },

  onTitleInput(e) {
    this.setData({ title: e.detail.value });
    this.checkCanSubmit();
  },

  onContentInput(e) {
    this.setData({ content: e.detail.value });
    this.checkCanSubmit();
  },

  onPetTypeChange(e) {
    this.setData({ petTypeIndex: e.detail.value });
    this.checkCanSubmit();
  },

  onPriceInput(e) {
    this.setData({ price: e.detail.value });
    this.checkCanSubmit();
  },

  onLocationInput(e) {
    this.setData({ location: e.detail.value });
    this.checkCanSubmit();
  },

  onStartDateChange(e) {
    this.setData({ startDate: e.detail.value });
    this.checkCanSubmit();
  },

  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
    this.checkCanSubmit();
  },

  checkCanSubmit() {
    const { title, content, price, location, startDate, endDate } = this.data;
    const canSubmit = title && content && price && location && startDate && endDate;
    this.setData({ canSubmit });
  },

  async onSubmit() {
    console.log('🚀 Submitting post...');
    
    if (!this.data.canSubmit) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }

    if (!this.checkLogin()) {
      return;
    }

    this.setData({ loading: true });

    try {
      const postData = {
        title: this.data.title,
        content: this.data.content,
        petType: this.data.petTypes[this.data.petTypeIndex],
        price: parseFloat(this.data.price),
        location: this.data.location,
        startDate: this.data.startDate,
        endDate: this.data.endDate
      };

      console.log('📤 Submitting post data:', postData);
      console.log('🔑 Using token:', app.globalData.token);
      console.log('👤 User ID:', app.globalData.userInfo.id);

      const result = await app.request('/posts', 'POST', postData);
      console.log('✅ Post created successfully:', result);
      
      wx.showToast({ 
        title: '发布成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            // 发布成功后跳转到首页
            wx.switchTab({ url: '/pages/index/index' });
          }, 1500);
        }
      });
    } catch (error) {
      console.error('❌ Submit post error:', error);
      if (error.status === 401) {
        wx.showToast({ 
          title: '登录已过期，请重新登录', 
          icon: 'none',
          success: () => {
            setTimeout(() => {
              wx.navigateTo({ url: '/pages/user/login/login' });
            }, 1500);
          }
        });
      } else {
        wx.showToast({ 
          title: error.error || '发布失败', 
          icon: 'none',
          duration: 3000
        });
      }
    } finally {
      this.setData({ loading: false });
    }
  }
});